const express = require("express");
const multer = require("multer")
const { db,genid } = require("./database/adapter")
const path = require("path")
const app = express();


const port = 4080;


//跨域开放
app.use(function(req,res,next){
    res.header("Access-Control-Allow-Origin","*");
    res.header("Access-Control-Allow-Headers","*");
    res.header("Access-Control-Allow-Methods",
    "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method === "OPTIONS") res.sendStatus(200);
    else next();
});


app.use(express.json());
const update = multer({
    dest:"./public/upload/temp"
});
app.use(update.any());

//指定静态资源路径
app.use(express.static(path.join(__dirname, "public")))


//验证token
const ADMIN_TOKEN_PATH = "/_token"
app.all("*", async (req, res, next) => {
    if (req.path.indexOf(ADMIN_TOKEN_PATH) > -1) {

        let { token } = req.headers;

        let admin_token_sql = "SELECT * FROM `admin` WHERE `token` = ?"
        let adminResult = await db.async.all(admin_token_sql,[token])
        if(adminResult.err != null || adminResult.rows.length == 0){
            res.send({
                code: 403,
                msg: "请先登录"
            })
            return 
        }else{
            next()
        }
    }else{
        next()
    }
})


//路由
app.use("/test",require("./router/testRouter"))
app.use("/admin",require("./router/AdminRouter"))
app.use("/register",require("./router/RegisterRouter"))
app.use("/category", require("./router/CategoryRouter"))
app.use("/blog", require("./router/BlogRouter"))
app.use("/upload", require("./router/UploadRouter"))

app.get("/",(req,res) => {
    res.send("hello--kkss")
});


app.listen(port,()=>{
    console.log(`ok,weGA==http://localhost:${port}`)
});


